package com.zxh.spDemo.web;

import com.zxh.spDemo.domain.User;
import com.zxh.spDemo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

	@Autowired
	UserService userService;

	@RequestMapping(value = "/index",method = RequestMethod.GET)
	public ModelAndView index(){
		ModelAndView index = new ModelAndView("index1");
		return index;
	}

	@RequestMapping(value = "/aaa",method = RequestMethod.GET)
	public String aaa(){
		return "aaaaaa";
	}

	@RequestMapping(value = "queryUid",method = RequestMethod.POST)
	@ResponseBody
	public Map queryUid(String uid){
		User user = new User();
		Integer num = new Integer(0);
		try {
			 user = userService.findByUsername(uid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(!(user==null)){
			num = 1;
		}
		HashMap<String, Integer> map = new HashMap<>();
		map.put("num",num);
		return map;
	}

	@RequestMapping(value = "/login",method = RequestMethod.POST)
	@ResponseBody
	public Map doLogin(HttpServletRequest request) {
		String uid = request.getParameter("uid");
		String pwd = request.getParameter("pwd");
		UsernamePasswordToken token = new UsernamePasswordToken(uid, pwd);
		HashMap<String, Object> map = new HashMap<>();
		try {
			request.getSession().setAttribute("username",uid);
			SecurityUtils.getSubject().login(token);
			map.put("result", "success");
			map.put("nickname", uid);
			return map;
		} catch (AuthenticationException e) {
			e.printStackTrace();
		}
		map.put("result", "fail");
		return map;
	}

	@RequestMapping(value = "/opencard",method = RequestMethod.POST)
	@ResponseBody
	public Map openCard(@RequestBody User user){
		Integer opencard = userService.openCard(user);
		HashMap<String, Object> map = new HashMap<>();
		if(opencard>0){
			map.put("result","success");
			return map;
		}else{
			map.put("result","fail");
			return map;
		}
	}

//	@RequestMapping(value = "/logout",method = RequestMethod.GET)
//	@ResponseBody
//	public Map logout(HttpServletRequest request){
//		request.getSession().removeAttribute("username");
//		HashMap<String, Object> map = new HashMap<>();
//		map.put("result","success");
//		return map;
//	}

	@RequestMapping(value = "/currentUser",method = RequestMethod.GET)
	@ResponseBody
	public Map currentUser(HttpServletRequest request){
		String username = (String)request.getSession().getAttribute("username");
		HashMap<Object, Object> map = new HashMap<>();
		map.put("username",username);
		return map;
	}

}
